<template>
<div class="All">
  <div class="searchBar">
    <!--    选择报修创建日期-->
    <el-date-picker class="createRepairsTime"
      v-model="searchAdminRepairs.creatTime"
      align="right"
      type="date"
      placeholder="选择报修日期"
      :picker-options="pickerOptions">
    </el-date-picker>
    <el-input class="elinput"
      placeholder="请输入报修人"
      v-model="searchAdminRepairs.user.userName"
      clearable>
    </el-input>
    <el-date-picker class="createRepairsTime"
      v-model="searchAdminRepairs.updateTime"
      align="right"
      type="date"
      placeholder="选择更新日期"
      :picker-options="pickerOptions">
    </el-date-picker>
    <el-input class="elinput"
      placeholder="请输入维修人"
      v-model="searchAdminRepairs.admin.adminName"
      clearable>
    </el-input>
    <!--可加一个select选择，显示状态，未休，已修，进行筛选list-->
    <el-select v-model="searchAdminRepairs.repairStatus" clearable placeholder="请选择修理状态" style="margin-left: 5px;">
      <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
      </el-option>
    </el-select>
    <el-button type="warning" @click="getList(1)" style="margin-left: 10px;">查 询</el-button>
  </div>
  <div class="list">
    <el-table
        :data="tableData.list"
        style="width: 100%"
        :row-class-name="tableRowClassName">
      <el-table-column
          type="index"
          label="序号"
          width="50">
      </el-table-column>
      <el-table-column
          prop="user.userName"
          label="报修人"
          width="150">
        <!-- 长文本缩略显示为XXX...-->
        <template slot-scope="scope">
            <span :title="scope.row.user?.userName">
              {{ scope.row.user?.userName ? (scope.row.user.userName.length > 5 ? scope.row.user.userName.substring(0,5) + '...' : scope.row.user.userName) : '——' }}
            </span>
        </template>
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="报修时间"
          :formatter="(row) => $options.filters.formatDateTime(row.creatTime)"
          width="200">
      </el-table-column>
      <el-table-column
          prop="admin.adminName"
          label="更新人"
          width="150">
        <template slot-scope="scope">
            <span :title="scope.row.admin?.adminName">
              {{ scope.row.admin?.adminName ? (scope.row.admin.adminName.length > 5 ? scope.row.admin.adminName.substring(0,5) + '...' : scope.row.admin.adminName) : '——' }}
            </span>
        </template>
      </el-table-column>
      <el-table-column
          prop="updateTime"
          label="更新时间"
          :formatter="(row) => $options.filters.formatDateTime(row.updateTime)"
          width="200">
      </el-table-column>
      <el-table-column prop="repairStatus" label="维修状态" width="150">
        <template #default="{ row }">
          <span v-if="row.repairStatus === true">已修理</span>
          <span v-else-if="row.repairStatus === false" style="color: red">未修理</span>
          <span v-else style="color: gray">未知状态</span>
        </template>
      </el-table-column>
      <el-table-column
          fixed="right"
          label="详情"
          width="150">
        <template slot-scope="scope">
          <el-button @click="handleLook(scope.row)" type="text" size="small">查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="200">
        <template slot-scope="scope">
        <!--修理按钮-->
          <el-button
              size="mini"
              type="danger"
              @click="handleRepair(scope.row)"
              :disabled="scope.row.repairStatus === true"
              :title="scope.row.repairStatus === true ? '不可修改' : ''">维修
          </el-button>
          <el-button
              size="mini"
              type="primary"
              @click="handleLookReturnInfo(scope.row)"
              :disabled="!(scope.row.followStatus === true || scope.row.repairStatus === true)"
              :title="scope.row.followStatus === true ? '已回访' : !(scope.row.followStatus === true || scope.row.repairStatus === true) ? '未回访，不可查看' : ''"
          >
            回访详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="pageNo">
    <el-pagination class="pageNum"
       background
       layout="prev, pager, next"
       @current-change="handlePageNumChange"
       :page-size="tableData.pageSize"
       :total="tableData.total"
       :current-page="tableData.pageNum">
    </el-pagination>
  </div>
<!--  查看报修详情信息弹窗-->
  <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      width="40%"
      :close-on-click-modal="true"
      @close="resetDialog"
  >
    <!--  @submit.native.prevent:model="updateFrom"是阻止updateForm表单自动提交防止请求两次  -->
    <el-form v-if="dialogMode ==='repair'" @submit.native.prevent:model="repairFrom" :rules="rules" ref="ruleFrom" label-width="100px" class="demo-ruleForm">
      <el-form-item label="维修费用:" prop="repairFee">
        <el-input  v-model="repairFrom.repairFee" placeholder="请输入维修费用" style="width: 200px;"></el-input>
      </el-form-item>
      <!-- ref暴露编辑器实例，供update方法使用-->
      <my-editor ref="editor" v-model="repairFrom.repairContent" :server="uploadSever" style="margin-top: 20px;"></my-editor>
    </el-form>
    <!-- dialog默认显示维修详情-->
    <div v-else-if="dialogMode === 'view'" class="view-content">
      <div class="repair-detail" style="position: relative; top: -30px">
        <!-- 维修状态 -->
        <div class="status-section">
          <h4>维修状态：</h4>
          <div
              class="status-badge"
              :class="{
            'repaired': adminRepair.repairStatus === true,
            'unrepaired': adminRepair.repairStatus === false,
            'unknown': adminRepair.repairStatus == null
          }"
          >
            {{ formatRepairStatus(adminRepair.repairStatus) }}
          </div>
        </div>
        <!-- 报修内容-->
        <div class="content-section">
          <h4>报修内容：</h4>
          <div v-html="adminRepair.userRepair?.content || '暂无报修内容'"></div>
        </div>
        <!-- 维修费用2位小数,同一行显示-->
        <div class="content-section" style="display: flex; align-items: center;">
          <h4 style="margin: 0; margin-right: 8px;">维修费用：</h4>
          <div v-if="adminRepair.repairFee !== null && adminRepair.repairFee !== undefined" style="color: inherit;">
            ¥{{ parseFloat(adminRepair.repairFee || 0).toFixed(2) }}
          </div>
          <div v-else style="color: gray;">暂无</div>
        </div>
        <!--维修时间-->
        <div class="content-section" style="display: flex; align-items: center;">
          <h4 style="margin: 0; margin-right: 8px;">维修时间:</h4>
          <div v-if="adminRepair.repairTime !== null && adminRepair.repairTime !== undefined" style="color: inherit;">
            {{adminRepair.repairTime}}
          </div>
          <div v-else style="color: gray;">暂无</div>
        </div>
        <!-- 维修内容-->
        <div class="content-section">
          <h4>维修内容：</h4>
          <div v-if="adminRepair.repairContent" v-html="adminRepair.repairContent"></div>
          <div v-else>暂无维修内容</div>
        </div>
      </div>
    </div>
    <!-- dialog显示回访详情-->
    <div v-else-if="dialogMode === 'lookReturnInfo'" class="view-content">
      <div class="repair-detail" style="position: relative; top: -30px">
        <!--分别显示受访人姓名、满意度、维修时间、备注-->
        <div class="content-section" style="display: flex; align-items: center;">
          <h4 style="margin: 0; margin-right: 8px;">受访人:</h4>
          <div v-if="adminRepair.user.userName!== null && adminRepair.user.userName !== undefined" style="color: inherit;">
            {{adminRepair.user.userName}}
          </div>
          <div v-else style="color: gray;">暂无受访人</div>
        </div>
        <div class="content-section" style="display: flex; align-items: center;">
          <h4 style="margin: 0; margin-right: 8px;">满意度:</h4>
          <div v-if="adminRepair.repairFollow.score!== null && adminRepair.repairFollow.score !== undefined" style="color: inherit;">
            <!-- 用星星显示满意度-->
            <el-rate
                v-model="adminRepair.repairFollow.score"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}">
            </el-rate>
          </div>
          <div v-else style="color: gray;">暂无满意度</div>
        </div>
        <div class="content-section" style="display: flex; align-items: center;">
          <h4 style="margin: 0; margin-right: 8px;">维修时间:</h4>
          <div v-if="adminRepair.repairFollow.updateTime!== null && adminRepair.repairFollow.updateTime !== undefined" style="color: inherit;">
            {{adminRepair.repairFollow.updateTime}}
          </div>
          <div v-else style="color: gray;">暂无维修时间</div>
        </div>
        <div class="content-section">
          <h4 style="margin: 0; margin-right: 8px;">业主评价:</h4>
          <div v-if="adminRepair.repairFollow.remark!== null && adminRepair.repairFollow.remark !== undefined" style="color: inherit;">
            {{adminRepair.repairFollow.remark}}
          </div>
          <div v-else style="color: gray;">暂无评价</div>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
            v-if="dialogMode==='repair'"
            type="primary"
            @click="save()">
            确定
        </el-button>
    </div>
  </el-dialog>
</div>
</template>
<script>
import MyEditor from "@/components/MyEditor.vue";

export default {
  name: "HandlerRepair",
  components: {MyEditor},
  filters: {//时间格式过滤器
    formatDateTime(value) {
      if (!value) return '';
      const date = new Date(value);
      // 使用UTC方法，避免时区转换
      const year = date.getUTCFullYear();
      const month = (date.getUTCMonth() + 1).toString().padStart(2, '0');
      const day = date.getUTCDate().toString().padStart(2, '0');
      const hours = date.getUTCHours().toString().padStart(2, '0');
      const minutes = date.getUTCMinutes().toString().padStart(2, '0');
      return `${year}-${month}-${day} `;
    },
  },
  data(){
    return {
      repairFlag:true,//修改表单是否可以提交
      // loading: false, //加载时等待
      dialogMode: 'view', // 弹窗模式，'add' 或 'view'
      dialogTitle: '查看报修信息',//弹窗标题
      dialogFormVisible: false,//弹窗显隐值，默认不出现false
      uploadSever: this.$basePath+'adminRepair/uploadWangEditorPic',//往后端上传图片的路径
      repairFrom: {//修理详情表单
        id:'',//维修事件id
        repairStaffId:'',//维修员工id
        repairFee:'',//维修费用
        repairContent:'',//维修内容，在线编辑器内容
      },
      tableData:[],
      searchAdminRepairs:{//搜索栏表单
        user:{
          userName:'',
        },
        creatTime:'',
        admin:{
          adminName:'',
        },
        updateTime:'',
        repairStatus:'',
      },
      adminRepair:{//list显示的data对象
        id:'',
        user:{
          userName:'',
        },
        creatTime:'',
        admin:{
          adminName:'',
        },
        repairTime:'',
        updateTime:'',
        repairStatus:'',
        followStatus:'',//加一个回访状态
        repairFee:'',
        repairContent:'',
        userRepair:{
          id:'',
          userId:'',
          content:'',
        },
        repairFollow:{//用来显示回访详情
          id:'',
          complaintId:'',
          updateTime:'',
          remark:'',
          score:'',
        },
      },
      options: [{//搜索栏维修状态
        value: true,
        label: '已修理'
      }, {
        value: false,
        label: '未修理'
      }],
      rules: {
        repairFee: [
          // 1. 非空校验（失焦时触发）
          {
            required: true,
            message: '维修费用不能为空',
            trigger: 'blur'
          },
          // 2. 数字格式校验（失焦时触发）（修改，原来的为空优先执行validator
          {
            validator: (rule, value, callback) => {
              if (value === '' || value === null || value === undefined) {
                // 如果为空，直接返回（required 规则会处理）
                callback(new Error('维修费用不能为空')); // 这里需要返回错误，否则会绕过required规则
                return;
              }
              // 检查是否为有效数字（禁止科学计数法，如 1e5）
              if (isNaN(Number(value)) || value.toString().includes('e') || value.toString().includes('E')) {
                callback(new Error('必须输入有效数字'));
                return;
              }
              // 检查整数和小数部分
              const parts = value.toString().split('.');
              const integerPart = parts[0];
              const decimalPart = parts[1] || '';
              // 整数部分不能超过 18 位
              if (integerPart.length > 18) {
                callback(new Error('整数部分不能超过18位'));
                return;
              }

              // 小数部分不能超过 2 位
              if (decimalPart.length > 2) {
                callback(new Error('小数精度不能超过2位'));
                return;
              }
              // 所有校验通过
              callback();
            },
            trigger: 'blur' // 失焦时校验
          }
        ],
      },
      pickerOptions: {
        disabledDate(time) {
          return false;//任何日期不禁用
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
    }
  },
  watch: {
    searchAdminRepairs: {
      handler(newVal) {
        const isEmpty =
            !newVal.creatTime &&
            !newVal.updateTime &&
            newVal.repairStatus === '' &&
            newVal.user.userName === '' &&
            newVal.admin.adminName === '';
        if (isEmpty) {
          this.getList(1);
        }
      },
      deep: true,
      immediate: true // 可选：初始化时也执行一次
    }
  },
  created() {
    this.getList(1);
  },
  methods: {
    getList(pageNum) {//上来就获取表格信息
      if(this.searchAdminRepairs.creatTime){
        const date = new Date(this.searchAdminRepairs.creatTime);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        this.searchAdminRepairs.creatTime = `${year}-${month}-${day}`;
      }
      if(this.searchAdminRepairs.updateTime){
        const date = new Date(this.searchAdminRepairs.updateTime);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        this.searchAdminRepairs.updateTime = `${year}-${month}-${day}`;
      }
      console.log("前端搜索栏表单==>",this.searchAdminRepairs);
      this.$axios.post("adminRepair/list",this.searchAdminRepairs,{params:{pageNum:pageNum}}).then((response) => {
        this.tableData = response.data.list;
        console.log("前端包检查-->==",this.tableData);
      });
    },
    save(){//提交修理信息
      console.log("合法不？==",this.repairFlag);
      console.log("那个事件id？==》",this.adminRepair.id);

      this.repairFrom.repairFee = Number(this.repairFrom.repairFee);

      this.repairFrom.id = this.adminRepair.id;//给提交的修改表单id赋值

      let adminId = (JSON.parse(window.localStorage.getItem("admin"))).id;//谁登陆取谁的id
      this.repairFrom.repairStaffId = adminId;//哪个员工维修的？从token取
      // 测试输出检查:
      console.log("要提交了修理信息是==》",this.repairFrom);
      //去后端修改维修事件
      this.$axios.post("adminRepair/handleRepair",this.repairFrom).then((response) => {
        this.dialogFormVisible = false;
        this.getList(1);
      });
    },
    handleLook(row){//查看报修信息，显示在线编辑器内容
      this.dialogMode = 'view'
      this.dialogTitle = '报修详情'
      this.adminRepair = row;//不用去数据库查单行adminRepair了，直接使用adminRepair显示当前行信息就行
      this.dialogFormVisible = true;
    },
    handlePageNumChange(pageNum) {//更改页码
      this.getList(pageNum);
    },
    tableRowClassName({row,rowIndex}) {//table方法，组件自带不能删
      return '';
    },
    formatRepairStatus(cellValue) {//这是查看报修详情的维修状态的格式化方法
      if (cellValue === true) return '已修理';
      if (cellValue === false) return '未修理';
      return '未知状态'; // 处理 null/undefined
    },
    handleRepair(row) {//点维修按钮到这
      this.dialogFormVisible = true;
      this.dialogMode = 'repair';
      this.dialogTitle = "物业报修"
      this.adminRepair = row;
      //重置维修表单
      this.repairFrom = {//修理详情表单
        id:'',//维修事件id
        repairStaffId:'',//维修员工id
        repairFee:'',//维修费用
        repairContent:'',//维修内容，在线编辑器内容
      }
    },
    handleLookReturnInfo(row){//点查看回访详情到这
      this.dialogFormVisible = true;
      this.dialogMode = 'lookReturnInfo'
      this.dialogTitle = '回访详情'
      this.adminRepair = row;
    },
    resetDialog(){//只要关闭弹窗就重置表单内容
      this.repairFrom = {
        id:'',
        repairStaffId:'',
        repairFee:'',
        repairContent:'',
      }
    },
  },
}
</script>
<style>
/*input样式*/
.elinput{
  width: 220px;
  margin: 5px;
}
/*分页按钮居中*/
.pageNum{
  display: flex;
  justify-content: center; /* 水平居中 */
  padding-top: 30px;
}
/*弹窗样式*/
.status-badge {
  padding: 5px 10px;
  border-radius: 4px;
  display: inline-block;
}

.repaired {
  background-color: #f0f9eb;
  color: #67c23a;
}

.unrepaired {
  background-color: #fef0f0;
  color: #f56c6c;
}

.unknown {
  background-color: #f4f4f5;
  color: #909399;
}
</style>